#include "pch.hpp"

#include "CBallMesh.hpp"
#include "hamster.h"
#include "animation.h"

animation ham_anim;

const int hamster::ANGLE_RANGE = 140;

void hamster::set_pos(sf::Vector2f pos)
{
	position = pos;
}

void hamster::load(sf::Vector2f pos)
{
	position = pos;
	float angle = DEGTORAD(float(rand() % 360));
	direction = sf::Vector2f(cos(angle), sin(angle));
	dead = false;
	animate = false;
	randomBlinkTime = 5;

	ham_anim.load("data/hamster.png", 48, 48, 5, 150, false);
}

void hamster::step()
{
	if(ham_timer.GetElapsedTime() > randomBlinkTime)
	{
		ham_timer.Reset();
		randomBlinkTime = rand() % 5 + 3;
	}
	position += direction;
	sf::Vector2f point;
	int cond = 0;
	float dist = poBallMesh->Distance(sf::Vector2f(0.0f, 384.0f), position);
	if (dist >= 230.0f)
	{
		cond = 1;
		point = sf::Vector2f(0.0f, 384.0f);
	}
	sf::Vector2i neighbour = poBallMesh->GetFirstNeighbour(poBallMesh->GetMapPosition(position));
	if (neighbour.x != -1)
	{
		cond = 2;
		point = poBallMesh->GetWorldPosition(neighbour);
	}
	if (cond)
	{
		if (cond == 2)
		{
			dist = poBallMesh->Distance(point, position);
		}
		sf::Vector2f vec((position.x - point.x) / dist, (position.y - point.y) / dist);
		float alpha = acos(vec.x);
		if (vec.y < 0.0f)
		{
			alpha = 2 * PI - alpha;
		}
		if (cond == 1)
		{
			alpha -= PI;
		}
		alpha = RADTODEG(alpha);
		alpha -= ANGLE_RANGE / 2;
		alpha += float(rand() % ANGLE_RANGE);
		float angle = DEGTORAD(alpha);
		direction = sf::Vector2f(cos(angle), sin(angle));
	}
}

void hamster::draw()
{
	ham_anim.SetPos(sf::Vector2f(position));
	ham_anim.draw(int(ham_timer.GetElapsedTime() * 1000.0f));
}